<?php
class Core_Controller_Autoloader {
	
	public function loadFile($className){
		
		$elementsToLoad = $this->parseElements($className);
		
		$elementsToLoad['directory'] = $this->getFolder($elementsToLoad);
		
		$filePath = $this->computeFilePath($elementsToLoad);
		
		$this->getFile($filePath, $elementsToLoad);
		
	}
	
	public function getFile($filePath, array $elementsToLoad){
		
		try {
			
			if(file_exists($filePath)){
				
				require_once $filePath;
			
			}
			else {
				
				throw new Exception("Framework could not find file '<strong>".$elementsToLoad['filename'].".php</strong>' in location: <string>".$filePath."</string>"); 
			
			}
			
		}
		catch(Exception $e){
			echo $e->getMessage();
		}
	}
	
	/**
	 * compute file path
	 * 
	 * @param array $elementsToLoad
	 * @return string $filePath
	 */
	public function computeFilePath(array $elementsToLoad){
		
		$filePath = basename(SERVER_ROOT) . "/" . basename(strtolower($elementsToLoad['functionality'])) . "/" . basename($elementsToLoad['directory']) . "/" . basename(strtolower($elementsToLoad['filename'])) . ".php";
		
		return $filePath;
		
	}
	
	/**
	 * get application tier folder
	 * 
	 * @param array $elementsToLoad
	 * @throws Exception
	 * @return string
	 */
	public function getFolder(array $elementsToLoad){
		
		$folder = strtolower($elementsToLoad['applicationTier']);
		
		try {
			
			switch($folder){
				
				case 'controller':
					$directory = basename("controllers");
					break;
				
				case 'library':
					$directory = basename("libraries");
					break;
				
				case 'driver':
					$directory = basename("drivers");
					break;
					
				case 'model':
					$directory = basename("models");
					break;
				
				case 'data':
					$directory = basename("data");
					break;
				
				default:
					throw new Exception("Invalid application tier '<strong>$folder</strong>'!!!");
			}
			
			return $directory;
			
		}
		catch(Exception $e){
			
			echo $e->getMessage();
		
		}
		
	}
	
	/**
	 * parse out filename where class should be located
	 * 
	 * @param string $className
	 * @return array $elementsToLoad
	 */
	public function parseElements($className){
		
		$elementsToLoad = array();
		
		list($elementsToLoad['filename'], $otherValues) = preg_split('/_/', strrev($className), 2);
		$elementsToLoad['filename'] = strrev($elementsToLoad['filename']);
		$otherValues = strrev($otherValues);
		
		list($elementsToLoad['applicationTier'], $elementsToLoad['functionality']) = preg_split('/_/', strrev($otherValues), 2);
		$elementsToLoad['applicationTier'] = strrev($elementsToLoad['applicationTier']);
		$elementsToLoad['functionality'] = strrev($elementsToLoad['functionality']);
		
		return $elementsToLoad;
		
	}
	
}